	/*
	* p2csv - Export all site or list permissions using jQuery and SPServices
	* Version 0.1.0
	* @requires jQuery v1.8+ and SPServices library
	*
	* Copyright (c) 2013 TarcisioGambin.net
	* Examples and docs at:
	* http://p2csv.codeplex.com
	* Licensed under the MIT license:
	* http://www.opensource.org/licenses/mit-license.php
	*/
	/**
	 * @description Export all site or list permissions using jQuery and SPServices
	 * @type jQuery
	 * @name p2csv
	 * @category Plugins/p2csv
	 * @author TarcisioGambin.net /tarcisio@learnpoint.net
	 */
	 
	 (function($) {

	 	$.fn.p2csv = function(options) {

		// base escope configuration
		// configuracao base de escopo
		var config = {
			scope : '',
			separator : ';',
		};
		$.extend(true, config, options); 

		// var definition
		// definicao de variaveis
		var valuableData;
		var csvFilename;
		var accountLogin;
		var accountName
		var groupName;
		var accountType;
		var permissionAccount;
		var accountMask;
		var myObjectName;
		var myObjectType;
		var siteName;
		var listName;
		const mimeType;


		// definicao de mascaras x permissoes. Maiores detalhes: http://msdn.microsoft.com/en-us/library/dd304243.aspx
		// masks and permissions definition. More details: http://msdn.microsoft.com/en-us/library/dd304243.aspx
		var permissionsMask = [
			{'mask':-1,'name':'Full Control'},
			{'mask':134287360,'name':'Limited Access'},
			{'mask':138612833,'name':'Read'},
			{'mask':1011028719,'name':'Collaboration'},
		]

		// verifica se a funcao iniciou no escopo do site ou lista
		// check if the function was started on 'list' or 'web' scope
		$().SPServices({
			operation : 'GetWeb',
			webURL : $().SPServices.SPGetCurrentSite(),
			async : false,
			completefunc : function(xData, Status) {
				$(xData.responseXML).find('Web').each(function() {
					siteName = $(this).attr('Title');
				});
			}
		});
		myObjectName = $().SPServices.SPGetCurrentSite();
		myObjectType = 'Web';
		csvFilename = siteName; 

		if (config.scope == 'list') {
			console.log('Getting this list permissions');
			$().SPServices({
				operation : 'GetList',
				listName : $().SPServices.SPListNameFromUrl(),
				async : false,
				completefunc : function(xData, Status) {
					$(xData.responseXML).find('List').each(function() {
						listName = $(this).attr('Title');
					});
				}
			});
			myObjectName = listName;
			myObjectType = 'List';
			csvFilename += ' - ' + listName;
		}

		// Obtem permissoes via web services relacionadas ao escopo
		// Get permissions from web services related to scope
		if (myObjectName) {
			$().SPServices({
				operation : "GetPermissionCollection",
				objectName : myObjectName,
				objectType : myObjectType,
				completefunc : function(xData, Status) {
					valuableData = 'User Name'+config.separator+'User Login'+config.separator+'User or Group Member?'+config.separator+'Permission'+config.separator+'Mask (to check); \n';
					$(xData.responseXML).find('Permission').each(function() {
						valuableData += formataValores($(this));
					});
					downloadFile();
				}
			});
		} else {
			alert("Oooops!\nIt's not possible to get list permissions.\nMake sure you are browsing a list URL! ");
		}

		// formata os valores para um padrao compativel com CSV
		// format the values in compatible CSV standard
		function formataValores(value) {
			if (value.attr('MemberIsUser') === 'True') {
				accountLogin = value.attr('UserLogin');
				accountType = "User";
				accountMask = value.attr('Mask');

				$().SPServices({
					operation : "GetUserInfo",
					userLoginName : $.trim(accountLogin),
					async : false,
					completefunc : function(xData, Status) {
						$(xData.responseXML).find("User").each(function() {
							accountName = $(this).attr("Name");
						});
					}
				});
				return formatPermissions(accountName, accountLogin, accountType, accountMask);
			} else {
				groupName = value.attr("GroupName");
				accountType = groupName;
				accountMask = value.attr('Mask');
				var valoresGrupo = '';

				$().SPServices({
					operation : "GetUserCollectionFromGroup",
					groupName : groupName,
					async : false,
					completefunc : function(xData, Status) {
						$(xData.responseXML).find("User").each(function() {
							accountName = $(this).attr("Name");
							accountLogin = $(this).attr("LoginName");
							valoresGrupo += formatPermissions(accountName, accountLogin, accountType, accountMask);
						});
					}
				});
				return valoresGrupo;
			}

			// formata as permissoes conforme valores das mascaras pre-definidas anteriormente
			// format the permissions strings according to previously predefined values from masks
			function formatPermissions(name, login, dataType, mask) {
				//permissionAccount = permissionsMask.filter(function (permission) { return permission.mask == mask })[0].name;
				if (checkIfExists()) {
					return name + config.separator + login + config.separator + dataType + config.separator + permissionAccount + config.separator + mask + "\n";
				} else {
					return name + config.separator + login + config.separator + dataType + config.separator + '**permission not configured**' + config.separator + mask + "\n";
				}

				function checkIfExists() {
					for ( i = 0; i < permissionsMask.length; i++) {
						if (permissionsMask[i].mask == mask) {
							permissionAccount = permissionsMask[i].name;
							return true;
						}
					}
				}
			}

		}

			// funcao para exportacao de dados e criacao do arquivo CSV 'on the fly'
			// function to export data and create CSV file 'on the fly'
			function downloadFile() {
				mimeType = 'text/csv';
				window.URL = window.webkitURL || window.URL;

				var blob = new Blob([valuableData], {
					type : mimeType
				});

				var link = document.createElement('a');
				link.download = 'Permissions of ' + csvFilename + ".csv";
				link.href = window.URL.createObjectURL(blob);
				link.textContent = 'Click here to download the ' + link.download;
				link.dataset.downloadurl = [mimeType, link.download, link.href].join(':');

				$('body').eq(0).html(link).css({
					'background-color' : '#ffffff',
					'color' : '#000000',
					'font-size' : '12px',
					'text-align' : 'center'
				});
			}

		};
	})
(jQuery);